package com.cnblogs.leizia.crm.configuration.listener;

import com.alibaba.fastjson.JSON;
import com.cnblogs.leizia.crm.settings.domain.DicValue;
import com.cnblogs.leizia.crm.settings.service.SysInitDicService;
import com.cnblogs.leizia.crm.settings.service.impl.SysInitDicServiceImpl;
import com.cnblogs.leizia.crm.utils.ServiceFactory;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.*;

/**
 * 数据字典监听器
 *
 * @author leizi
 * @create 2021-03-01 22:05
 */
public class SysInitListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {

        SysInitDicService sysInitDicService = (SysInitDicService) ServiceFactory.getService(new SysInitDicServiceImpl());
        Map<String, List<DicValue>> dicValues = sysInitDicService.getDicValues();

        Map<String, String> map = new HashMap<>();

        // 将获取的数据字典保存在servletContext域对象中
        ServletContext servletContext = sce.getServletContext();
        Set<String> keys = dicValues.keySet();
        for (String key : keys) {
            servletContext.setAttribute(key, dicValues.get(key));
        }

        // 读取Stage2Possibility.properties文件内容，作为创建交易页面的可能性值
        ResourceBundle stage2Possibility = ResourceBundle.getBundle("Stage2Possibility");
        Set<String> keySet = stage2Possibility.keySet();
        for (String key : keySet) {
            String value = stage2Possibility.getString(key);
            map.put(key, value);
        }
        String stage2Json = JSON.toJSONString(map);
        servletContext.setAttribute("stage2", stage2Json);

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}
